//
//  HomeViewController.m
//  FH JOANNEUM
//
//  Created by Katharina Kluge on 25/07/12.
//  Modified by Daniel Hösele
//  Copyright (c) 2014 Daniel Hösele. All rights reserved.
//

#import "HomeViewController.h"
#import "ScheduleViewController.h"
#import "Event.h"
#import "EventTableViewCell.h"
#import "EventManager.h"
#import "Schedule.h"
#import "SettingsManager.h"

@interface HomeViewController ()

@end

@implementation HomeViewController

@synthesize eventArray, tableView, scheduleButton, newsButton;

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateData) name:@"DoUpdate" object:nil];
    
    // Set the image in the title view of the navigation item
    UIImageView *titleView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"FHJ_Logo.png"]];
    
    [self.navigationItem setTitleView:titleView];
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    
    // Set the backgrund image
    //UIImageView *backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"glass.jpg"]];
    //[self.view addSubview:backgroundView];
    //[self.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"fhred.jpeg"]]];
    
    // style the tableview
    [self.tableView setRowHeight:70];
    [self.tableView registerNib:[UINib nibWithNibName:@"EventTableHomeViewCell" bundle:nil] forCellReuseIdentifier:@"EventCellIdentifier"];
    [self.tableView registerNib:[UINib nibWithNibName:@"EventTableViewCell_iPad" bundle:nil] forCellReuseIdentifier:@"EventCellIdentifier_iPad"];
    
    
    [self.tableView setSeparatorColor:[UIColor blackColor]];
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [self.tableView setAllowsSelection:NO];
}

- (void)updateData
{
    //NSLog(@"Update");
    eventArray = nil;
    [self.tableView reloadData];
    /*
     the spinning wheel, which indicates that the events are loading right now
     */
    UIActivityIndicatorView *loadingIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    if(self.view.center.x > 300)
        [loadingIndicator setCenter:CGPointMake(self.view.center.y+180,self.view.center.x-100)];
    else
        [loadingIndicator setCenter:CGPointMake(self.view.center.x, self.view.center.y+145)];
    [loadingIndicator startAnimating];
    [self.view addSubview:loadingIndicator];
    
    
    //get group from settingsmanager
    NSString *group = [[SettingsManager sharedInstance] group];
    NSString *groupId = [group substringFromIndex:[group length] - 1];
    
    /*
     shows the events on the display if no error occured
     */
    self.eventArray = [[NSMutableArray alloc] init];
    EventManager *eventManager = [[EventManager alloc] init];
    [eventManager fetchEvents:^(NSArray *eventsArray, NSError *error){
        [loadingIndicator stopAnimating];
        if (!error) {
            NSDate *date = [NSDate date];
            NSTimeInterval ti = [date timeIntervalSince1970];
            int daysToShow=1;
            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
            [dateFormatter setDateFormat:@"'Today:'"];
            //[dateFormatter setDateFormat:@"dd.MM - EEE"];
            for (int i=0; i<daysToShow; i++) {
                NSDate *startDate = [NSDate dateWithTimeIntervalSince1970:ti+86400*i];
                NSString *name = [dateFormatter stringFromDate:startDate];
                Schedule *s = [[Schedule alloc] initWithName:name];
                [self.eventArray addObject:s];
            }
            for (Event* event in eventsArray) {
                for (int i=0; i<daysToShow; i++) {
                    /*
                    //soft dev start = 1416901500
                    
                    NSInteger time = round(ti);
                    NSLog(@"%ld", (long)time);
                    
                    if(event.end >= ti && event.end < ti+i*86400)
                        [[[self.eventArray objectAtIndex:i] events] addObject:event];
                    */
                    if(event.start < ti+(i+1)*86400-(long)ti%86400 && event.start > ti+i*86400-(long)ti%86400)
                        [[[self.eventArray objectAtIndex:i] events] addObject:event];
                    
                    if(![group isEqualToString:@"Show all"] && [group length] > 0) {
                        
                        //NSLog( @"%@", group );
                        
                        if([event.type hasPrefix:@"G"] && ![event.type isEqualToString:group])
                            [[[self.eventArray objectAtIndex:i] events] removeObject:event];
                        if([event.type hasPrefix:@"S"] && ![[event.type substringFromIndex:[event.type length] - 1] isEqualToString:groupId])
                            [[[self.eventArray objectAtIndex:i] events] removeObject:event];
                    }
                }
            }
            for (Schedule *s in self.eventArray) {
                if([s.events count] == 0)
                    [s.events addObject:[[Event alloc] initWithDict:NULL]];
            }
            [self.tableView reloadData];
            
        } else {
            //UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Notice" message:[error localizedDescription] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
            //[alertView show];
        }
    }];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

#pragma mark - Table view data source

- (NSString*)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return [[self.eventArray objectAtIndex:section] title];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return [self.eventArray count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [[[self.eventArray objectAtIndex:section] events] count];
}

- (UITableViewCell *)tableView:(UITableView *)touchTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *CellIdentifier;
    if(self.view.bounds.size.width<768) {
        CellIdentifier = @"EventCellIdentifier";
    } else {
        CellIdentifier = @"EventCellIdentifier_iPad";
    }
    EventTableViewCell *cell = [touchTableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    Event *event = [[[self.eventArray objectAtIndex:indexPath.section] events] objectAtIndex:indexPath.row];
    
    [cell.descriptionLabel setText:event.getDesc];
    [cell.timeLabel setText:event.getTitle];
    
    return cell;
}

@end